Function.RegisterNamespace("System.EnvironmentStrategy");

System.EnvironmentStrategy.Phantom=function(){
    var _system=null;
    var _process=null;

    // IEnvironmentStrategy members
    this.Execute=function(command,parameters,voidOutput){
        if(!_process)_process=require("child_process");
        var result=null;
        _process.execFile(command, parameters, null, function (err, stdout, stderr){
          result=stdout||stderr;
        });
        if(!voidOutput)return result+'';        
    };

    this.Exit=function(errorCode){
        phantom.exit(errorCode);
    };

    this.GetNewLine=function(){
        return "\n";
    };

    this.GetParameters=function(){
        var args={
            named:{},
            unnamed:[]
        };
        var params=_system.args;
        // First arg is js file
        for(var i=1;i<params.length;i++){
            var param=String.Trim(params[i]+'');
            if(String.StartsWith(param,'/')&&String.Contains(param,':')){
                param=String.TrimStart(param,'/').split(':');
                args.named[param[0].toLowerCase()]=param.slice(1).join(':');
            }else args.unnamed.push(param);
        }
        return args;
    };
    
    this.GetWorkingDirectory=function(){
        return System.IO.Path.Normalize(require('fs').workingDirectory);
    };

    this.Write=function(message1,message2,messageN){
        _system.stdout.write(Array.prototype.slice.call(arguments,0).join(''));
    };
    
    this.WriteError=function(message1,message2,messageN){
        _system.stderr.write(Array.prototype.slice.call(arguments,0).join(''));
    };

    // IStrategySpecification members
    this.IsSatisfiedBy=function(candidate){
        if(typeof(phantom)!="undefined"&&typeof(require)=="function"){
            _system=require("system");
            System.Script.ScriptLoader.Strategies.Remove(System.Script.ScriptLoadStrategy.Dom);
            return true;
        }
        return false;
    };
};

System.EnvironmentStrategy.Phantom.Implement(System.EnvironmentStrategy.IEnvironmentStrategy,'System.EnvironmentStrategy.Phantom');
System.EnvironmentStrategy.Phantom.Implement(System.Script.Strategy.IStrategySpecification,'System.EnvironmentStrategy.Phantom');

System.Environment.Strategies.Add(System.EnvironmentStrategy.Phantom,0);
